import { useCallback, useRef, useState } from "react";
import { request } from "shared/requests";
import { useLatestRef } from "shared/hooks";
import { BASE_API_URL } from "../constants";

export default function useQuery<T>(body: {
  url: string;
  model?: string;
  type: number;
}) {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<any>(null);
  const [data, setData] = useState<T | null>(null);
  const cancelRef = useRef<() => void>();

  const bodyRef = useLatestRef(body);
  const fetchHandler = useCallback(() => {
    const abortController = new AbortController();
    cancelRef.current = () => abortController.abort(new Error("CancelRequest"));
    requestAnimationFrame(() => {
      setLoading(true);
      setData(null);
      setError(null);
    });
    request<T>(BASE_API_URL + "/sz/create", {
      method: "post",
      headers: { "content-type": "application/json" },
      data: bodyRef.current,
      signal: abortController.signal,
    })
      .then((text) => {
        console.log({ text });
        setData(text);
      })
      .catch((err) => {
        setError(err);
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);

  const cancel = useCallback(() => {
    cancelRef.current?.();
  }, []);

  return { loading, error, data, query: fetchHandler, cancel };
}
